package com.byxy.computer.student.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.byxy.computer.student.entity.HomeWork;
import com.byxy.computer.student.entity.LessonMaterial;
import com.byxy.computer.student.entity.Student;
import com.byxy.computer.student.json.AjaxObject;
import com.byxy.computer.student.service.HomeWorkService;
import com.byxy.computer.student.service.LessonMaterialService;
import com.byxy.computer.student.service.StudentService;

/**
 * @author Daniel
 * @E-Mail iva0512@gmail.com
 * @Date 2016年9月25日
 */
@Controller
@RequestMapping("html5/student")
public class Html5StudentController {

	@Autowired
	private StudentService studentService;
	@Autowired
	private HomeWorkService homeWorkService;
	@Autowired
	private LessonMaterialService lessonMaterialService;

	// 学生交作业
	@RequestMapping(value = "student_upload.do", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObject upload(MultipartFile attach, HttpServletRequest req) {
		Student student = (Student) req.getSession().getAttribute("student");
		AjaxObject ajax = new AjaxObject(AjaxObject.OK);
		String strDate = DateFormat.getDateInstance().format(new Date());
		Student s = studentService.get(student);
		String path = "/upload/" + strDate + "/" + s.getUid() + "_" + s.getUsername();
		String realpath = req.getSession().getServletContext().getRealPath(path);
		String filename = attach.getOriginalFilename();
		File ff = new File(realpath);
		if(!ff.exists()){
			if(!ff.mkdirs()){
				System.out.println(realpath);
			}
		}
		
		if (filename.length() > 0) {
			File f = new File(realpath + "/" + filename);
//			System.out.println(realpath + "/" + filename);
			try {
				FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
				HomeWork h = new HomeWork(s.getUid(), strDate + "/" + s.getUid() + "_" + s.getUsername() + "/" + filename, filename, attach.getSize() / 1024.0f);
				studentService.upload(s, strDate + "/" + s.getUid() + "_" + s.getUsername() + "/" + filename, (int) attach.getSize());
				homeWorkService.save(h);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			ajax.setResult(AjaxObject.ERROR);
			ajax.setMsg("交作业失败");
		}
		return ajax;
	}

	// 作业列表
	@ResponseBody
	@RequestMapping(value = "list_homework.do", method = RequestMethod.GET)
	public List<HomeWork> listHomeWork(HttpServletRequest req) {
		Student s = (Student) req.getSession().getAttribute("student");
		return homeWorkService.findByUId(s.getUid());
	}

	// 作业列表
	@ResponseBody
	@RequestMapping(value = "list_Material.do", method = RequestMethod.GET)
	public List<LessonMaterial> listMaterial() {
		return lessonMaterialService.listAll();
	}

	// 作业列表
	@ResponseBody
	@RequestMapping(value = "getStudent.do", method = RequestMethod.GET)
	public Student getStudent(HttpServletRequest req) {
		Student s = (Student) req.getSession().getAttribute("student");
		if(s!=null){
			s = studentService.get(s);
		}
		return s;
	}

	@ResponseBody
	@RequestMapping(value = "dologin.do", method = RequestMethod.POST)
	public AjaxObject login(String uid, HttpServletRequest req) {
		AjaxObject ajax = new AjaxObject();
		req.getSession().removeAttribute("student");
		if (uid == null) {
			ajax.setResult(AjaxObject.ERROR);
			ajax.setMsg("学号不能为空");
		} else {
			Student student = studentService.getByUid(uid);
			if (student == null) {
				ajax.setResult(AjaxObject.ERROR);
				ajax.setMsg("找不到对应的学号，请重新输入。");
			} else {
				ajax.setResult(AjaxObject.OK);
				ajax.setMsg("");
				student.setComputername(req.getRemoteHost());
				Student s = studentService.sign(student);
				req.getSession().setAttribute("student", s);
			}
		}
//		System.out.println(ajax.getResult() + "  " + ajax.getMsg());
		return ajax;
	}

	// 作业列表
	@ResponseBody
	@RequestMapping(value = "download.do", method = RequestMethod.GET)
	public AjaxObject downloadMaterial(String id, HttpServletRequest request) {
		AjaxObject ajax = new AjaxObject();
		LessonMaterial l = lessonMaterialService.findById(id);
		if (l != null) {
			ajax.setResult(AjaxObject.OK);
			String ctx = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/upload/" + l.getUrl();
			ajax.setMsg(ctx);
		} else {
			ajax.setResult(AjaxObject.ERROR);
			ajax.setMsg("找不到资料文件，该文件可以已经删除了");
		}
		return ajax;
	}
	
	@ResponseBody
	@RequestMapping(value = "downloadByIo", method = RequestMethod.GET)
	public void xz(String url, HttpServletRequest request,HttpServletResponse response){
		String realpath = request.getSession().getServletContext().getRealPath("/");
		int len = url.lastIndexOf("/");
		if (len > 0) {
			String name = url.substring(len + 1);
			File file = new File(realpath + "/upload/Material/" + name);
			if (file.exists()) {
				try {
					String realname = new String(name.getBytes("gbk"), "ISO-8859-1");
					response.reset();
					response.setCharacterEncoding("utf-8");
//					response.setContentType("multipart/form-data");
					response.setContentType("application/x-msdownload");
					response.setHeader("Content-Disposition", "attachment;fileName=" + realname);
					InputStream inputStream = new FileInputStream(file);
					int fileLength = (int) file.length();
					response.setContentLength(fileLength);
					OutputStream os = response.getOutputStream();
					byte[] b = new byte[2048];
					int length;
					while ((length = inputStream.read(b)) > 0) {
						os.write(b, 0, length);
					}
					inputStream.close();
					os.close();
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
	}
}
